<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :currentPage="page.currPage"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :change-page="changePage"
        :editFunc="handleEdit"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd"
            >新增</el-button
          >
        </template>
        <!-- 角色状态 -->
        <template #roleStatus="{ rows }">
          <el-tag type="success" v-if="rows.roleStatus === 1">启用</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="closeDialog"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        :options="options"
        :edit="isEdit"
        :update="updateData"
        @closeDialogP="closeDialog"
      />
    </el-dialog>
    <el-dialog title="详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData" @closeDialogP="visible1 = false">
        <!-- 角色权限 -->
        <template #resourceBoList="{ rows }">
          <span v-for="(item, index) in rows.resourceBoList" :key="index">
            <span>{{ item.resourceName }}</span
            ><span v-if="index < rows.resourceBoList.length - 1">，</span>
          </span>
        </template>
      </TableDetail>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import { User } from "@/types/user";
import {
  fetchRoleResourceData,
  fetchgetRoleResource,
  fetchRoleResourceCreate,
  fetchDeleteRoleResource,
  fetchRoleResourceDetail,
} from "@/api/roleManage";
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";
import { FormOption, FormOptionList } from "@/types/form-option";

// 查询相关
const query = reactive({
  keyword: "",
});
const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "角色名：", prop: "keyword",placeholder:'请输入角色名' },
]);
const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  { type: "index", label: "序号", width: 55, align: "center" },
  { prop: "roleId", label: "角色ID" },
  { prop: "roleName", label: "角色名" },
  { prop: "roleStatus", label: "状态" }, //状态 0-停用 1-启用
  { prop: "createTime", label: "创建时间" },
  { prop: "operator", label: "操作", width: 300, fixed: "right" },
]);
const page = reactive({
  currPage: 1,
  size: 10,
  total: 0,
});
const tableData = ref([]);
const getData = async () => {
  let params = {
    currPage: page.currPage,
    size: page.size,
    keyword: query.keyword,
  };
  const res = await fetchRoleResourceData(params);
  console.log("用户角色列表");
  console.log(res.data);
  tableData.value = res.data.data.records;
  page.total = res.data.data.total;
  console.log(page.total);
};
getData();

// 分页
const changePage = (val: number) => {
  console.log("点击分页---歌单分类管理");

  page.currPage = val;
  console.log(page.currPage);
  getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: "100px",
  span: 24,
  list: [
    { type: "input", label: "角色名", prop: "roleName", required: true,placeholder:'请输入角色名' },
    {
      type: "select",
      label: "角色权限",
      prop: "resourceBoList",
      multiple: true,
      opts: [],
      placeholder:'请选择角色权限'
    },
  ],
});

const resourceVoListPre = ref([]); //角色资源信息列表
// 获取系统资源页面路由
const getRoleResource = async () => {
  const res = await fetchgetRoleResource({});
  console.log("获取系统资源页面路由");
  console.log(res.data);
  let list = res.data.data;
  list.forEach((item) => {
    item.value = item.resourceCode;
    item.label = item.resourceName;
  });
  options.value.list[1].opts = list;
  resourceVoListPre.value = list;
};

getRoleResource();

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({
  resourceBoList: [],
});

// 新增
const handleAdd = (row) => {
  console.log("新增");
  rowData.value = { ...row };
  isEdit.value = false;
  visible.value = true;
};

// 编辑
const handleEdit = async (row) => {
  console.log("编辑");
  // 先获取详情
  let params = {
    roleId: row.roleId,
  };
  const res = await fetchRoleResourceDetail(params);
  console.log("获取角色详情");
  console.log(res);
  const resData = res.data.data;
  row.resourceBoList = resData.resourceVoList;
  // resData.roleId = row.roleId
  rowData.value = { ...row };
  console.log("先看看是什么呢");
  console.log(rowData);

  // rowData.value.resourceBoList = resData.resourceVoList
  let arr = [];
  // if(rowData.value.resourceBoList.length>0){
  //   let obj = {
  //     value:'',
  //     label:'',
  //   }
  rowData.value.resourceBoList.forEach((item) => {
    // item.value = item.resourceCode;
    // item.label = item.resourceName;
    item = item.resourceCode;
    console.log("查一查");
    console.log(item);
    arr.push(item);
  });

  // }
  rowData.value.resourceBoList = arr;
  // // 重新整理选择框的格式
  console.log("ziuuuu---");
  console.log(rowData.value);
  isEdit.value = true;
  visible.value = true;
};
const updateData = async (data) => {
  console.log("kkkk");
  // console.log(resourceVoList.value)
  console.log(data);
  const resourceBoList2 = [];
  resourceVoListPre.value.forEach((item, index) => {
    data.resourceBoList.forEach((item2, index2) => {
      if (item.resourceCode === item2) {
        resourceBoList2.push(item);
      }
    });
  });

  console.log("是什么呢？？？？");
  console.log(resourceBoList2);
  data.resourceBoList = resourceBoList2;
  let datas = {};
  let obj = {
    roleStatus: 1, //状态 0-停用 1-启用
    // resourceBoList:resourceBoList //新获取的资源列表
  };
  let editObi = { roleId: data.roleId }; //用户角色id
  if (isEdit.value) {
    datas = { ...data, ...obj, ...editObi };
  } else {
    datas = { ...data, ...obj };
  }
  console.log("最终编辑或者新增的数据---是");
  console.log(datas);
  const res = await fetchRoleResourceCreate(datas);
  console.log("新增角色");
  console.log(res.data);
  closeDialog();
  getData();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: [],
});
const handleView = async (row) => {
  // 先获取详情
  let params = {
    roleId: row.roleId,
  };
  const res = await fetchRoleResourceDetail(params);
  console.log("获取角色详情");
  console.log(res);
  const resData = res.data.data;
  row.resourceBoList = resData.resourceVoList;
  // resData.roleId = row.roleId
  viewData.value.row = { ...row };
  viewData.value.list = [
    {
      prop: "roleId",
      label: "角色ID",
    },
    {
      prop: "roleName",
      label: "角色名",
    },
    {
      prop: "resourceBoList",
      label: "角色权限",
    },
    {
      prop: "createTime",
      label: "创建时间",
    },
  ];
  visible1.value = true;
};

// 删除相关
const handleDelete = async (row) => {
  console.log("删除");
  console.log(row);
  let datas = {
    id: row.roleId,
  };
  const res = await fetchDeleteRoleResource(datas);
  if (res.data.code == 0) {
    ElMessage.success("删除成功");
    getData();
  }
};
</script>

<style scoped></style>
